<template>
  <view-box ref="viewBox" body-padding-bottom="55px" style="background: #f2f2f2">
    <!-- <img v-if="course" :src="$apiUrl + '/storage/' + course.thumb" alt="" class="cover"> -->
    <div v-if="course" class="banner" :style="{ backgroundImage: 'url(' + $apiUrl + '/storage/' + course.thumb +')' }"></div>
    <tab :line-width="1">
      <tab-item selected @on-item-click="show = 'catalog'">课程目录</tab-item>
      <tab-item @on-item-click="show = 'detail'">课程详情</tab-item>
    </tab>
    <template  v-if="course">
      <div class="catalog" v-if="show === 'catalog'">
        <group title="课程目录">
          <template v-for="(item, index) in course.catalogs" >
            <cell is-link :border-intent="true" :arrow-direction="item.active ? 'down' : 'up'"  @click.native="item.active = !item.active">
            <div slot="title" class="title">
              <span>{{item.order}}</span>
              {{item.name}}
            </div>
            </cell>
            <box v-if="item.active" gap="20px 20px 5px 50px">
              <div class="flex-box" @click="showCourse(item)">
                <span>
                  <i class="iconfont icon-shipin" v-if="item.type === 1"></i>
                  <i class="iconfont icon-tuwen" v-if="item.type === 3"></i>
                  <i class="iconfont icon-yinpin" v-if="item.type === 2"></i> 单节购买：
                  <span class="price" v-if="item.price > 0">￥{{item.price}}</span>
                  <span class="price" v-if="item.price <= 0">免费</span>
                </span>
                <span class="purchase">
                  立即学习
                </span>
              </div>
            </box>
          </template>
        </group>
      </div>
      <div class="detail" v-if="show === 'detail'">
        <box gap="10px">
          <h3 class="p-name">{{course.name}}</h3>
          <div class="p-count">
            <span>
              <i class="iconfont icon-icon-"></i> <span> {{course.pv}}次浏览</span>
            </span>
            <span>
              <i class="iconfont icon-time"></i> <span> {{course.length_of_time}}分钟</span>
            </span>
            <span>
              <i class="iconfont icon-pinglun"></i> <span> {{course.comment_count}}条评论</span>
            </span>
          </div>
          <div class="p-price">
            <span class="price" v-if="course.price > 0">￥{{course.price}}</span>
            <span class="price" v-if="course.price <= 0">免费</span>
          </div>
        </box>
        <div class="gutter"></div>
        <box gap="10px">
          <div class="content" v-html="course.body"></div>
        </box>
      </div>
    </template>
    <!-- 视频 -->
    <div v-transfer-dom>
      <popup v-model="showVideo" position="right" width="100%" height="100%">
        <template v-if="course && courseContent">
          <h1>{{course.name}}</h1>
          <h2>{{courseContent.order}}、{{courseContent.name}}</h2> 
        </template> 
        <img class="logo" src="../components/images/logo.png">
        <d-player v-if="options" :options="options" ref="player" @play="play"></d-player>
        <div class="close" @click="close('video')">
          <i class="iconfont icon-fanhui"></i>
          <span>返回列表页</span>
        </div>
      </popup>
    </div>
    <!-- 音频 -->
    <div v-transfer-dom>
      <popup v-model="showAudio" position="right" width="100%" height="100%">
        <template v-if="course && courseContent">
          <h1>{{course.name}}</h1>
          <h2>{{courseContent.order}}、{{courseContent.name}}</h2>
        </template>  
        <img class="logo" src="../components/images/logo.png">
        <aplayer v-if="music" :music="music" ref="aplayer"></aplayer>
        <div class="close" @click="close('audio')">
          <i class="iconfont icon-fanhui"></i>
          <span>返回列表页</span>
        </div>
      </popup>
    </div>
    <!-- 图文 -->
    <div v-transfer-dom>
      <popup v-model="showPost" position="right" width="100%" height="100%">
        <template v-if="course && courseContent">
          <h1>{{course.name}}</h1>
          <h2>{{courseContent.order}}、{{courseContent.name}}</h2> 
          <img class="logo" src="../components/images/logo.png">
          <box gap="10px">
            <div class="content" v-html="courseContent.body"></div>
          </box>
          <div class="close" @click="close('post')">
            <i class="iconfont icon-fanhui"></i>
            <span>返回列表页</span>
          </div>
          </template> 
      </popup>
    </div>
    <!-- 购买 -->
    <div v-transfer-dom>
      <popup v-model="showBuy" height="460px" is-transparent v-if="course && userInfo">
        <div class="pay">
        <group title="支付方式">
          <radio :options="payWay" v-model="submitData.pay_code">
            <template slot-scope="props" slot="each-item">
              <p class="pay-type">
                <i :class="props.icon" class="pay-icon"></i> {{ props.label }}
                <span v-if="props.index === 1" style="font-size: 13px; color: #999; margin-left: 5px;">可用余额{{userInfo.balance}}元</span>
              </p>
            </template>
          </radio>
        </group>
        <group title="使用积分">
          <x-switch :disabled="availableIntegralNumber <= 0" :title="'可使用'+availableIntegralNumber+'积分抵扣'+availableIntegralPrice+'元'" v-model="submitData.use_integral"></x-switch>
          <cell :title="userInfo.level.name" :value="userInfo.level.discount_desc"></cell>
          <cell title="应付金额" :value="'￥' + orderAmount"></cell>
         </group>
         <div style="padding:20px 15px;">
          <x-button type="primary" @click.native="pay()" :disabled="paying" :show-loading="paying">支付</x-button>
          <x-button @click.native="cancelPay">取消</x-button>
         </div>
        </div>
      </popup>
    </div>
    <div slot="bottom" class="action-bar vux-1px-b vux-1px-t" v-if="course">
      <div class="p-home-btn vux-1px-r" @click="$router.push('/')">
        <span class="iconfont icon-shouye2"></span>
        <span>首页</span>
      </div>
      <div class="p-store-btn vux-1px-r" @click="collection()">
        <span class="iconfont icon-shoucang"></span>
        <span>收藏</span>
      </div>
      <div class="p-chat-btn" @click="$router.push('/chat/' + course.user.id)">
        <span class="iconfont icon-kefu" style="color:#e02e24;"></span>
        <span>咨询</span>
      </div>
      <div v-if="course.price > 0 && !course.purchased" class="p-direct-btn" @click="buy('App\\Course', course)">
        <span class="p-price">￥{{course.price}}</span>
        <span>立即购买</span>
      </div>
      <div v-else class="p-cart-btn" @click="showCourse(course.catalogs[0])">
        <span class="iconfont icon-xuexi"></span>
        <span>开始学习</span>
      </div>
    </div>
  </view-box>
</template>
<style>
</style>
<script>
  import 'DPlayer/dist/DPlayer.min.css'
  import { INTEGRAL_EXCHANGE_RATIO } from '@/config'
  import DPlayer from 'vue-dplayer'
  import Aplayer from 'vue-aplayer'
  import logo from '../components/images/logo.png'
  import { TransferDom, ViewBox, Tab, TabItem, Box, Group, Cell, XButton, Popup, Radio, XSwitch } from 'vux'
  export default {
    directives: {
      TransferDom
    },
    data () {
      return {
        paying: false,
        disabled: false,
        logo: logo,
        show: 'catalog',
        showBuy: false,
        showVideo: false,
        showAudio: false,
        showPost: false,
        courseId: null,
        course: null,
        courseContent: null,
        options: {},
        player: null,
        music: null,
        aplayer: null,
        submitData: {
          integral: 0,
          exchange_integral: 0,
          use_integral: false,
          price: 0,
          courseable_type: 'App\\Course',
          courseable_id: 0,
          pay_code: 'WXPAY'
        }
      }
    },
    computed: {
      userInfo () {
        return this.$store.getters.userInfo
      },
      availableIntegralNumber () {
        if (!this.userInfo) {
          return 0
        }
        return (this.submitData.exchange_integral > this.userInfo.integral) ? this.userInfo.integral : this.submitData.exchange_integral
      },
      availableIntegralPrice () {
        return this.availableIntegralNumber * INTEGRAL_EXCHANGE_RATIO
      },
      orderAmount () {
        if (this.userInfo) {
          let discount = this.userInfo.level.discount > 0 ? this.userInfo.level.discount : 1
          let price = this.submitData.price * 100 * discount / 100
          if (this.submitData.use_integral) {
            price = price - this.availableIntegralPrice
          }
          if (price < 0) {
            price = 0
          }
          return price
        }
        return 0
      },
      payWay () {
        return [{
          icon: 'iconfont icon-weixinzhifu',
          key: 'WXPAY',
          value: '微信支付'
        }, {
          icon: 'iconfont icon-zhanghuyue',
          key: 'BALANCE',
          value: '余额支付',
          disabled: true
        }]
      }
    },
    components: {
      XSwitch,
      Radio,
      ViewBox,
      Tab,
      TabItem,
      Box,
      Group,
      Cell,
      XButton,
      Popup,
      DPlayer,
      Aplayer
    },
    mounted () {
      this.courseId = this.$route.params.course
      this._getData()
    },
    methods: {
      buy (courseableType, course) {
        this.submitData.courseable_type = courseableType
        this.submitData.courseable_id = course.id
        this.submitData.exchange_integral = course.exchange_integral
        this.submitData.price = course.price
        this.showBuy = true
      },
      pay () {
        this.paying = true
        this.$http.post('/userCourse', {
          use_integral: this.submitData.use_integral,
          integral: this.availableIntegralNumber,
          pay_code: this.submitData.pay_code,
          courseable_type: this.submitData.courseable_type,
          courseable_id: this.submitData.courseable_id
        }).then((response) => {
          if (response.data.pay_status) {
            this.paying = false
            this.showBuy = false
            this.$vux.toast.show('购买成功')
            this._getData()
          } else {
            this._pay(response.data)
          }
        }).catch((error) => {
          console.log(error)
          this.paying = false
        })
      },
      cancelPay () {
        this.showBuy = false
        this.paying = false
      },
      collection () {
        this.$http.post('/collections', {collectionable_id: this.course.id, collectionable_type: 'App\\Course'}).then((response) => {
          this.$vux.toast.show('收藏成功')
        }).catch((error) => {
          console.log(error)
        })
      },
      _pay (json) {
        let callpay = () => {
          if (typeof WeixinJSBridge === 'undefined') {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
              document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
            }
          } else {
            onBridgeReady()
          }
        }
        let onBridgeReady = () => {
          WeixinJSBridge.invoke('getBrandWCPayRequest', json, (res) => {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              this.paying = false
              this.showBuy = false
              this.$vux.toast.show('购买成功')
              this._getData()
            } else {
              this.paying = false
              this.showBuy = false
            }
          })
        }
        callpay()
      },
      showCourse (item) {
        if (!item || !this.course) {
          this.$vux.toast.show({
            text: '课程正在更新中',
            type: 'cancel'
          })
          return false
        }
        if (!this._checkPay(this.course, item)) {
          // 购买
          this.submitData.courseable_type = 'App\\CataLog'
          this.submitData.courseable_id = item.id
          this.submitData.exchange_integral = item.exchange_integral
          this.submitData.price = item.price
          this.showBuy = true
          return false
        }
        this.courseContent = item
        if (item.type === 1) {
          this.$nextTick(() => {
            this.player = this.$refs.player.dp
            this.player.switchVideo({
              url: this.$apiUrl + '/storage/' + item.video_path
              // pic: this.$apiUrl + '/storage/' + this.course.thumb
            })
            this.player.toggle()
          })
          this.showVideo = true
        } else if (item.type === 2) {
          this.music = {
            title: item.name,
            artist: this.course.user.name,
            src: this.$apiUrl + '/storage/' + item.audio_path,
            pic: logo
          }
          this.$nextTick(() => {
            this.aplayer = this.$refs.aplayer
            this.aplayer.toggle()
          })
          this.showAudio = true
        } else {
          this.showPost = true
        }
      },
      _checkPay (course, item) {
        if (course.price <= 0 && item.price <= 0) {
          return true
        } else if (course.purchased) {
          return true
        } else if (item.price <= 0) {
          return true
        } else if (item.purchased) {
          return true
        } else {
          return false
        }
      },
      close (type) {
        if (type === 'audio') {
          this.aplayer.pause()
          this.showAudio = false
        } else if (type === 'video') {
          this.player.pause()
          this.showVideo = false
        } else {
          this.showPost = false
        }
      },
      play () {
        // this.player.pause()
        console.log('play callback')
      },
      _getData () {
        this.$vux.loading.show()
        this.$http.get('/courses/' + this.courseId).then((response) => {
          this.$vux.loading.hide()
          this.course = response.data
          // this.switchThumb()
        }).catch((error) => {
          console.log(error)
          this.$vux.loading.hide()
        })
      }
    }
  }
</script>
<style>
  .content img {
   max-width: 100% !important;
  }
</style>
<style scoped lang="less">
  .banner {
    height: 250px;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
  }
  .p-name {
    font-weight: normal;
  }
  .p-count {
    color: #999;
    padding: 10px 0;
    height: 22px;
    line-height: 16px;
    display: flex;
    justify-content: space-between;
    .share {
      color: #449fe7;
      border: 1px solid #449fe7;
      padding: 2px 10px;
      border-radius: 5px;
    }
  }
  .p-price {
    display: flex;
    justify-content: space-between;
    .price {
      font-size: 22px;
    }
  }
  .price {
    color: #ff6700;
  }
  .gutter {
    height: 15px;
    margin-top: 10px;
    background: #EFEFF4;
  }
  .title {
    span {
      color: #999;
      margin-right: 10px;
    }
  }
  .flex-box {
    display: flex;
    justify-content: space-between;
    .iconfont {
      color: #449fe7;
      font-weight: bold;
      font-size: 18px;
    }
    .purchase {
      padding: 2px 15px;
      border-radius: 2px;
      background: #ff6600;
      color: #fff;
      font-size: 14px;
    }
  }
  .close {
    text-align:center; 
    color: #999;
    position: fixed;
    top: 1rem;
    left: 1rem;
  }
  .logo {
    width: 36px;
    height: 36px;
    position: fixed;
    top: 1rem;
    right: 1rem;
  }
  h1 {
    text-align:center;
    font-size: 30px;
    color: #42b983;
    margin: 45px 10px 10px;
  }
  h2 {
    font-size: 16px;
    color: #555;
    margin: 0 10px;
    text-align: center;
  }
  .dplayer {
    width: 90%;
    margin: 50px auto;
  }
  .aplayer {
    width: 90%;
    margin: 50px auto;
  }
  .action-bar {
    position: fixed;
    bottom: 0;
    height: 54px;
    background: #fff;
    width: 100%;
    display: flex;
  }
  .action-bar span {
    display: block;
    text-align: center;
    line-height: 1;
  }
  .action-bar .iconfont {
    font-size: 20px;
    margin-bottom: 2px;
  }
  .p-home-btn, .p-store-btn, .p-chat-btn {
    width: 70px;
    padding-top: 8px;
    color: #58595b;
    font-size: 14px;
  }
  .p-direct-btn {
    flex:1;
    padding-top: 8px;
    background-color: #e02e24;
    color: #fff;
    font-size: 15px;
  }
  .p-group-btn, .p-cart-btn{
    flex: 1;
    padding-top: 8px;
    background-color: #e02e24;
    color: #fff;
    font-size: 15px;
  }
  .p-price {
    margin-bottom: 4px;
    font-weight: 500;
    font-size: 17px;
  }
  .pay {
    width: 95%;
    background-color: #fff;
    height: 440px;
    margin: 0 auto;
    border-radius: 5px;
    padding-top: 10px;
  }
  .pay-type {
    line-height: 25px;
  }
  .pay-icon {
    color: #04BE02;
    font-size: 25px;
    margin-right: 10px;
  }
</style>